import maya.cmds as mc
import maya.cmds as cmds

import maya.mel as mel
import maya.OpenMaya as OpenMaya
####
import sys
import re
sys.path.append('U:/RiggerAdderMenu/RC_scriptsCommands')
sys.path.append('U:/RC_Scripts/SystemUpdate')




class updateWin():
    def importInfo(self):
        import updateVis
        reload(updateVis)
        update=updateVis.updateVis()
        update.aa()
    def updateWin(self):

        updateSettingWindow = 'updateOriginalSettings'
        if mc.window(updateSettingWindow,ex = True):
            mc.deleteUI(updateSettingWindow)

        mc.window(updateSettingWindow,widthHeight=(300, 200),t='R&C commandTools_v1.01',menuBar = True,rtf=True,s=True)
        frame1 = mc.frameLayout( label='update choice', labelAlign='top', borderStyle='in' )
        mc.rowColumnLayout('Main',numberOfColumns=1,w=300,cal = (5,'center'),m=True)
        mc.button('sys_update',w=300,h=30,c=lambda *args:self.sys_updateWin())

        mc.button('updateVis',w=300,h=30,c=lambda *args:self.importInfo())
        mc.button('joint Hide setting oper',w=300,h=30,c=lambda *args:self.hideJoint())
        mc.rowColumnLayout('hideAB',numberOfColumns=2,w=150,cal = (5,'center'),m=True)
        mc.button('hide Posituib_A_B',w=148,h=30,c=lambda *args:self.hidePosition_A_B(0))
        mc.button('show Posituib_A_B',w=148,h=30,c=lambda *args:self.hidePosition_A_B(1))
        mc.button('geo_doubleSided_single',w=148,h=30,c=lambda *args:self.doubleSide(0))
        mc.button('geo_doubleSided_double',w=148,h=30,c=lambda *args:self.doubleSide(1))

        mc.setParent('..')
        mc.button('create SN PH',w=148,h=30,c=lambda *args:self.createSNPH('set_ctrl'))
        mc.button('_EX check and Edit',w=148,h=30,c=lambda *args:self.check_EX())
        mc.button('LO_HI_Trans except eye_HI',w=148,h=30,c=lambda *args:self.LOHI_Trans())
        mc.button('rnkRigUtil',w=148,h=30,c=lambda *args:self.rnkRigUtil())


        mc.showWindow()

    def hideJoint(self):

        try:
                if mc.objExists('visibility_zero')==True:
                    visZero='visibility_zero'
                if mc.objExists('Visibility_zero')==True:
                    visZero='Visibility_zero'

                if mc.objExists('visibility_ctrl_zero')==True:
                    visZero='visibility_ctrl_zero'
                if mc.objExists('Visibility_ctrl_zero')==True:
                    visZero='Visibility_ctrl_zero'

                if mc.attributeQuery('joints_vis',node=visZero,ex=True)==False:

                    mc.addAttr(visZero,ln='joints_vis',at='double',min=0,max=1,dv=0,k=True)
                jntlist = mc.ls(type='joint')
                print(jntlist)
                for x in jntlist:
                    try:
                        #if re.search("_ik_", x)  :
                                mc.setAttr('%s.%s'%(x,'overrideEnabled') , lock=False)
                                mc.setAttr('%s.%s'%(x,'overrideEnabled') , 1)
                                mc.setAttr('%s.%s'%(x,'overrideLevelOfDetail'),lock = False)
                                mc.setAttr('%s.%s'%(x,'overrideLevelOfDetail') ,1)
                                mc.connectAttr(str(visZero)+'.joints_vis',x+'.overrideLevelOfDetail',f=1)
                        #else:
                        #        mc.setAttr('%s.%s'%(x,'overrideEnabled') , lock=False)
                        #        mc.setAttr('%s.%s'%(x,'overrideEnabled') , 1)
                        #        mc.setAttr('%s.%s'%(x,'overrideLevelOfDetail'),lock = False)
                        #        mc.setAttr('%s.%s'%(x,'overrideLevelOfDetail') ,0)
                        #        mc.setAttr(x+'.visibility',lock = False)
                        #        mc.connectAttr(str(visZero)+'.joints_vis',x+'.visibility',f=1)
                    except:
                        pass
        except :
                mc.error("visibility_zero.joints_vis is already added~!")

    def hidePosition_A_B(self,v=0):
        """"""
        posABList=['positionA','positionB']
        for x in posABList:
                ctrlShapeList = mc.listRelatives(x,s=True)
                for i in ctrlShapeList:
                    mc.setAttr('%s.%s'%(i,'visibility') ,v)
                #mc.setAttr('%s.%s'%(x,'dispGeometry') ,v)

        sys.stderr.write("%s:is:%d"%(posABList,v))
    def doubleSide(self,v=0):
        """"""
        jntlist = mc.ls(type='mesh')
        for x in jntlist:
                mc.setAttr('%s.%s'%(x,'doubleSided') ,v)
        sys.stderr.write("geo:doubleSided:%d"%(v))

    def check_EX(self):
        global tss
        setWindow = 'not_EX_geo'
        if mc.window(setWindow,ex = True):
                mc.deleteUI(setWindow)
        mc.window(setWindow,widthHeight=(300, 200),t='not_EX_geo_v1.01',menuBar = True,rtf=True,s=True)
        mc.paneLayout()
        tss=mc.textScrollList( numberOfRows=8, allowMultiSelection=True,ams=1,sc=lambda *args:self.EXselectItems())
        mc.popupMenu(mm=1)
        mc.menuItem(l="reNameAll",c=lambda *args:self.EXrenameAllItems())
        mc.menuItem( divider=True )
        mc.menuItem(l="reNameSelect",c=lambda *args:self.EXrenameSelectItems())
        mc.menuItem( divider=True )
        mc.showWindow(setWindow)
        mc.textScrollList(tss,e=1,ra=1)
        geoList= mc.ls(type=['mesh','nurbsSurface'])
        for geo in geoList:
                geoModel=mc.listRelatives(geo,p=1)[0]
                fullpath=mc.listRelatives(geoModel,fullPath=1)
                headGrp=re.split("\|",fullpath[0])[2]

                if (headGrp=="of3d_rig") and (geoModel[-3:]!="_EX"):
                        print(geoModel)
                        print(geoModel[-3:])
                        if geoModel[-3:]=='_LO':
                            pass
                        else:
                            mc.textScrollList(tss,e=1, append=geoModel)
        mc.select(cl=1)

    def EXselectItems(self):
        selectItems=mc.textScrollList(tss,q=1, si=1)
        mc.select(selectItems[0])
    def EXrenameAllItems(self):
        allItems=mc.textScrollList(tss,q=1, ai=1)
        for items  in allItems:
                if items[-3:]!="_EX":
                        mc.rename(items,items+"_EX")
                        sys.stderr.write( " rename %s"%items)
        self.check_EX()
    def EXrenameSelectItems(self):
        allItems=mc.textScrollList(tss,q=1, si=1)
        for items  in allItems:
                if items[-3:]!="_EX":
                        mc.rename(items,items+"_EX")
                        sys.stderr.write( " rename %s"%items)
        self.check_EX()

    ############
    ##
    #
    def LOHI_Trans(self):
        allMeshShape=mc.ls(type=['mesh','nurbsSurface'])

        if mc.objExists('visibility')==True:
            visCtrl='visibility'
        if mc.objExists('Visibility')==True:
            visCtrl='Visibility'
        if mc.objExists('visibility_ctrl')==True:
            visCtrl='visibility_ctrl'
        if mc.objExists('Visibility_ctrl')==True:
            visCtrl='Visibility_ctrl'
        for am in allMeshShape:
            mesh=mc.listRelatives(am,p=True)[0]

            if '_LO' == mesh[-3::]:
                mc.setAttr(str(mesh)+'.visibility',lock=False)
                mc.setDrivenKeyframe(str(mesh)+'.visibility', cd=str(visCtrl)+'.mode',dv=1,v=0)
                mc.setDrivenKeyframe(str(mesh)+'.visibility', cd=str(visCtrl)+'.mode',dv=2,v=1)
                mc.setDrivenKeyframe(str(mesh)+'.visibility', cd=str(visCtrl)+'.mode',dv=3,v=0)
                mc.setAttr(str(mesh)+'.visibility',lock=True)

            if '_HI' == mesh[-3::]:
                mc.setAttr(str(mesh)+'.visibility',lock=False)
                mc.setDrivenKeyframe(str(mesh)+'.visibility', cd=str(visCtrl)+'.mode',dv=1,v=1)
                mc.setDrivenKeyframe(str(mesh)+'.visibility', cd=str(visCtrl)+'.mode',dv=2,v=0)
                mc.setDrivenKeyframe(str(mesh)+'.visibility', cd=str(visCtrl)+'.mode',dv=3,v=0)
                mc.setAttr(str(mesh)+'.visibility',lock=True)
##############################eye visibility
        if mc.objExists('r_eye_HI') == 1 and mc.objExists('r_eye_HI')  ==1:
                r_eye_key =mc.listConnections('r_eye_HI.v',type="animCurve")[0]
                l_eye_key  =mc.listConnections('l_eye_HI.v',type="animCurve")[0]
                mc.keyframe(r_eye_key,absolute=1, valueChange =1,index=(1,1))
                mc.keyframe(l_eye_key,absolute=1, valueChange =1,index=(1,1))
##############################eye visibility
    def sys_updateWin(self):
        import RC_updateBodyBuilder
        reload(RC_updateBodyBuilder)

        a=RC_updateBodyBuilder.RC_updateBodyBuilder()
        a.RC_updateBodyBuilderWin()
    def rnkRigUtil(self):
        if mc.objExists('rnk_rig')==True and mc.objExists('visibility_ctrl')==True:
            mc.setAttr('rnk_rig.visibility',lock=False)
            if mc.listConnections('rnk_rig.v') == None:
                mc.connectAttr("visibility_ctrl.rnk_control_vis",'rnk_rig.v')
            import rnkRigUtil
            reload(rnkRigUtil)
            rnkRigUtil.createConstraints()
            rnkRigUtil.createVisibilityAttribute()
            rnkRigUtil.runFromShelf()
        else:
            sys.stderr.write('there is no "rank_rig" or "visibility_ctrl"')

    def createSNPH(self,ctrlset = 'set_ctrl'):
        cbAttrList = ['translateX','translateY','translateZ','rotateX','rotateY','rotateZ']
        allCtrls = cmds.sets(ctrlset,q=True)
        for ctrl in allCtrls:
            if '_SN' in ctrl or '_PH' in ctrl:
                pass
            else:
                ctrlParent = cmds.listRelatives(ctrl,p=True)[0]
                if '_SN' in ctrlParent:
                    pass
                else:
                    if cmds.nodeType(ctrl) == 'joint':
                        cmds.setAttr(ctrl+'.jointOrient',l=False)
                        jx = cmds.getAttr(ctrl+'.jointOrientX')
                        jy = cmds.getAttr(ctrl+'.jointOrientY')
                        jz = cmds.getAttr(ctrl+'.jointOrientZ')
                    else:
                        pass
                    positionValue = cmds.xform(ctrl,q=True,ws=True,t=True)
                    snGrp = cmds.group(ctrl,n = ctrl+'_SN')
                    cmds.move(positionValue[0],positionValue[1],positionValue[2],snGrp+'.rotatePivot')
                    cmds.move(positionValue[0],positionValue[1],positionValue[2],snGrp+'.scalePivot')
                    cmds.sets(snGrp,add=ctrlset)
                    phGrp = cmds.group(snGrp,n = ctrl+'_PH')
                    cmds.move(positionValue[0],positionValue[1],positionValue[2],phGrp+'.rotatePivot')
                    cmds.move(positionValue[0],positionValue[1],positionValue[2],phGrp+'.scalePivot')
                    cmds.sets(phGrp,add=ctrlset)
                    if ctrl == 'visibility':
                        attrList = []
                    else:
                        attrList = cmds.listAttr(ctrl,k=True,u=True)
                    if attrList != []:
                        for attr in attrList:
                            if attr in cbAttrList:
                                cmds.setAttr(ctrl+'.'+attr,0)
                                if cmds.nodeType(ctrl) == 'joint':
                                    cmds.setAttr(ctrl+'.jointOrientX',jx)
                                    cmds.setAttr(ctrl+'.jointOrientY',jy)
                                    cmds.setAttr(ctrl+'.jointOrientZ',jz)
                                    #cmds.setAttr(ctrl+'.jointOrient',l=True)
                                else:
                                    pass
                            else:
                                pass
                    else:
                        pass

    def ctrlQuery(self):
        global ts
        setWindow = 'ctrlSet'
        if mc.window(setWindow,ex = True):
                mc.deleteUI(setWindow)
        mc.window(setWindow,widthHeight=(300, 200),t='ctrlSet_v1.01',menuBar = True,rtf=True,s=True)
        mc.paneLayout()
        ts=mc.textScrollList( numberOfRows=8, allowMultiSelection=True,ams=1,sc=lambda *args:self.selectItems())
        mc.popupMenu(mm=1)
        mc.menuItem(l="append",c=lambda *args:self.appendItems())
        mc.menuItem( divider=True )
        mc.menuItem(l="remove",c=lambda *args:self.removeItems())
        mc.menuItem( divider=True )
        mc.showWindow(setWindow)
        mc.textScrollList(ts,e=1,ra=1)
        mc.select("*_ctrl","*_PH","*_SN")
        ctrlList=mc.ls(sl=1)
        ctrlSet=mc.sets("set_ctrl",q=1)
        for ctrl in ctrlList:
                if ctrl not in ctrlSet:
                        print ctrl
                        mc.textScrollList(ts,e=1, append= ctrl)
        for ctrl in ctrlSet:
                if ctrl[-5:]!="_ctrl" and ctrl[-3:]!="_PH" and ctrl[-3:]!="_SN":
                        mc.textScrollList(ts,e=1, append= ctrl)
        mc.select(cl=1)
    def selectItems(self):
        selectItems=mc.textScrollList(ts,q=1, si=1)
        mc.select(selectItems[0])
    def appendItems(self):
        selectItems=mc.textScrollList(ts,q=1, si=1)
        for item in selectItems:
                mc.sets(item,add="set_ctrl")
                mc.textScrollList(ts,e=1, ri=item)
                sys.stderr.write( " %s add to set_ctrl"%item)
    def removeItems(self):
        selectItems=mc.textScrollList(ts,q=1, si=1)
        for item in selectItems:
                mc.sets(item,rm="set_ctrl")
                mc.textScrollList(ts,e=1, ri=item)
                sys.stderr.write( " %s remove to set_ctrl"%item)